package org.xshop.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.xshop.bean.Order;
import org.xshop.bean.OrderPay;
import org.xshop.model.OrderList;
import org.xshop.model.OrderState;
import org.xshop.model.PayOrder;
import org.xshop.model.TOrder;
import org.xshop.model.TParam;
import org.xshop.service.ITOrderService;
import org.xshop.service.ITOrderStateService;

import com.alibaba.fastjson.JSON;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;
import top.ibase4j.core.base.AppBaseController;
import top.ibase4j.core.support.pay.WxPayment;
import top.ibase4j.core.util.DataUtil;
import top.ibase4j.core.util.InstanceUtil;
import top.ibase4j.core.util.WebUtil;

/**
 * <p>
 * 商城 前端控制器
 * </p>
 *
 * @author ShenHuaJie
 * @since 2017-05-14
 */
@Controller
@RequestMapping("/app/order/")
@Api(tags = "Order", value = "APP订单接口", description = "APP-个人中心-我的订单")
public class TOrderController extends AppBaseController<TOrder, ITOrderService> {
    @Autowired
    private ITOrderStateService orderStateService;

    @ApiOperation(value = "订单列表", notes = "获取当前用户的所有订单", produces = MediaType.APPLICATION_JSON_VALUE, response = TOrder.class)
    @RequestMapping(value = "getMyOrderList.api", method = { RequestMethod.GET, RequestMethod.POST })
    public Object query(HttpServletRequest request, OrderList order) {
        Map<String, Object> param = WebUtil.getParameter(request);
        Long id = getCurrUser(request);
        if (DataUtil.isNotEmpty(id)) {
            param.put("memberId", id);
        }
        Assert.notNull(param.get("memberId"), "用户ID不能为空.");
        Object result = service.queryAll(param);
        return setSuccessModelMap(result);
    }

    @ApiOperation(value = "订单详情", notes = "获取指定ID订单的详情", produces = MediaType.APPLICATION_JSON_VALUE, response = TOrder.class)
    @RequestMapping(value = "orderDetail.api", method = { RequestMethod.GET, RequestMethod.POST })
    public Object get(HttpServletRequest request, TParam param) {
        param = WebUtil.getParameter(request, TParam.class);
        Assert.notNull(param.getId(), "订单ID不能为空.");
        TOrder order = new TOrder();
        order.setId(param.getId());
        order.setMemberId(getCurrUser(request));
        return super.get(order);
    }

    @RequestMapping(value = "delOrder.api", method = { RequestMethod.POST })
    @ApiOperation(value = "删除订单", notes = "删除指定ID的订单", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object delete(HttpServletRequest request) {
        Map<String, Object> param = WebUtil.getParameter(request);
        Assert.notNull(param.get("ids"), "订单ID不能为空.");
        Long memberId = getCurrUser(request);
        Assert.notNull(memberId, "用户ID不能为空.");
        param.put("memberId", memberId);
        service.updateFromDelete(param);
        return setSuccessModelMap();
    }

    @RequestMapping(value = "create.api", method = { RequestMethod.POST })
    @ApiOperation(value = "创建订单", notes = "创建订单;如果来自购物车,则清除购物车中的相应商品", response = TOrder.class, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object update(HttpServletRequest request, Order param,
        @RequestParam(defaultValue = "0") @ApiParam("是否来自购物车(0|1)") String fromCart) {
        param = WebUtil.getParameter(request, Order.class);
        Long id = getCurrUser(request);
        if (DataUtil.isNotEmpty(id)) {
            param.setMemberId(id);
        }
        param.setSkuType("1");
        Assert.notNull(param.getMemberId(), "用户ID不能为空.");
        Assert.notNull(param.getAddressId(), "收货地址ID不能为空.");
        Assert.notNull(param.getSkuList(), "商品列表不能为空.");
        Object result = service.create(param, new Boolean[] { fromCart.equals("1") });
        return setSuccessModelMap(result);
    }

    @RequestMapping(value = "goodsPayReturn.api", method = { RequestMethod.POST })
    @ApiOperation(value = "支付回调", notes = "支付回调(WEB支付)", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiIgnore
    public Object pay(HttpServletRequest request, OrderPay param) {
        param = WebUtil.getParameter(request, OrderPay.class);
        Long id = getCurrUser(request);
        if (DataUtil.isNotEmpty(id)) {
            param.setMemberId(id);
        }
        Assert.notNull(param.getMemberId(), "用户ID不能为空.");
        Assert.notNull(param.getOrderNo(), "订单号不能为空.");
        Assert.notNull(param.getPayType(), "支付类型不能为空.");
        Assert.notNull(param.getPayOrderId(), "支付流水号不能为空.");
        service.pay(param);
        return setSuccessModelMap(InstanceUtil.newHashMap("bizeCode", 1));
    }

    @RequestMapping(value = "createPayOrder.api", method = { RequestMethod.POST })
    @ApiOperation(value = "支付平台下单", notes = "用户选择好支付方式，准备付款的时候，调用此接口，返回支付平台需要的签名串\n"
            + "客户端再使用此签名串向支付平台发起支付请求", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object createWxOrder(HttpServletRequest request, PayOrder param) {
        param = WebUtil.getParameter(request, PayOrder.class);
        Long id = getCurrUser(request);
        if (DataUtil.isNotEmpty(id)) {
            param.setMemberId(id);
        }
        Assert.notNull(param.getMemberId(), "用户ID不能为空.");
        Assert.notNull(param.getOrderId(), "订单ID不能为空.");
        Assert.notNull(param.getPayType(), "付款方式不能为空.");
        if (DataUtil.isEmpty(param.getIp())) {
            param.setIp(WebUtil.getHost(request));
        }
        Object result = service.createPayOrder(param.getOrderId(), param.getPayType(), 
            param.getIp());
        return setSuccessModelMap(result);
    }

    @RequestMapping(value = "getOrderState.api", method = { RequestMethod.POST, RequestMethod.GET })
    @ApiOperation(value = "获取订单状态(并更新)", notes = "获取指定ID订单的状态(实时查询第三方支付平台，更新支付状态)", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object updateState(HttpServletRequest request, OrderState param) {
        param = WebUtil.getParameter(request, OrderState.class);
        Long id = getCurrUser(request);
        if (DataUtil.isNotEmpty(id)) {
            param.setMemberId(id);
        }
        Assert.notNull(param.getMemberId(), "用户ID不能为空.");
        Assert.notNull(param.getOrderId(), "订单ID不能为空.");
        Object result = orderStateService.updateState(param.getOrderId(), param.getMemberId());
        return setSuccessModelMap(result);
    }

    @RequestMapping(value = "wxPayReturn.api", method = { RequestMethod.POST })
    @ApiOperation(value = "微信回调", notes = "微信回调接口", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiIgnore
    public Object wxPayReturn(HttpServletRequest request) {
        Map<String, String> result = InstanceUtil.newHashMap("return_code", "<![CDATA[SUCCESS]]>");
        try {
            Map<String, Object> param = WebUtil.getParameter(request);
            Assert.notNull(param.get("appid"), "应用APPID不能为空.");
            Assert.notNull(param.get("mch_id"), "商户号不能为空.");
            orderStateService.updateWxPayReturn(param);
        } catch (Exception e) {
            logger.error("", e);
            result = InstanceUtil.newHashMap("return_code", "<![CDATA[FAIL]]>");
            result.put("return_msg", "<![CDATA[" + e.getMessage() + "]]>");
        }
        logger.info(JSON.toJSONString(result));
        return ResponseEntity.ok(WxPayment.toXml(result));
    }

    @RequestMapping(value = "aliPayReturn.api", method = { RequestMethod.POST })
    @ApiOperation(value = "支付宝回调", notes = "支付宝回调接口", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiIgnore
    public Object aliPayReturn(HttpServletRequest request) {
        Map<String, String> result = InstanceUtil.newHashMap("msg", "SUCCESS");
        try {
            Map<String, Object> param = WebUtil.getParameter(request);
            Assert.notNull(param.get("app_id"), "应用APPID不能为空.");
            Assert.notNull(param.get("out_trade_no"), "商户号不能为空.");
            orderStateService.updateAliPayReturn(param);
        } catch (Exception e) {
            logger.error("", e);
            result = InstanceUtil.newHashMap("msg", "erorr");
        }
        logger.info(JSON.toJSONString(result));
        return ResponseEntity.ok(result);
    }
}
